package com.zwan.oam_rtc.utils.process;

import lombok.extern.slf4j.Slf4j;

import java.io.InputStreamReader;
import java.io.LineNumberReader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Slf4j
public class ProcUtil {


    private static Map<String,ProcessThread> threadMap = new HashMap<>();

    public static void runModule(String cmd, String workdir){
        ProcessThread processThread = new ProcessThread();
        processThread.setCommand(cmd);
        processThread.setWorkDir(workdir);
        processThread.start();
    }

    public static void runSipp(){
        String command = String.format("su - sipp -c \"/home/sipp/bin/zwdog\"");
        String workdir = "/home/sipp";
        runModule(command,workdir);
    }

    public static void runZwan() {
        String command = String.format("su - zwan -c \"/home/zwan/bin/zwdog\"");
        String workdir = "/home/zwan";
        runModule(command,workdir);
    }

    public static void runRtpp() {
        String command = String.format("su - rtpp -c \"/home/rtpp/bin/zwdog\"");
        String workdir = "/home/rtpp";
        runModule(command,workdir);
    }

    public static void runMs() {
        String command = String.format("su - ms -c \"/home/ms/bin/zwdog\"");
        String workdir = "/home/ms";
        runModule(command,workdir);
    }

    public static void runRtsp() {
        String command = String.format("/home/rtsp/rtsp start");
        String workdir = "/home/rtsp";
        runModule(command,workdir);
    }


    public static String getLicense(String cpuid) {
        String line = null;
        try {
            List<String> cmds = new ArrayList<String>();
            cmds.add("sh");
            cmds.add("-c");
            String command = String.format("su - zwanlic -c 'tool -E " + cpuid + "'");
            cmds.add(command);
            ProcessBuilder pb = new ProcessBuilder(cmds);
            pb.redirectErrorStream(true);
            Process process = pb.start();
            InputStreamReader ir = new InputStreamReader(process.getInputStream());
            LineNumberReader input = new LineNumberReader(ir);
            while ((line = input.readLine()) != null) {
                log.info("got license: "+line);
                return line;
            }
        } catch (java.io.IOException e) {
            log.error("IOException " + e.getMessage());
        }
        return line;
    }
}
